package com.kai.server.handler.message.impl;

import com.kai.common.domain.Message;
import com.kai.common.domain.Response;
import com.kai.common.domain.ResponseHeader;
import com.kai.common.domain.Task;
import com.kai.common.enumeration.ResponseType;
import com.kai.common.utils.ProtoStuffUtil;
import com.kai.server.handler.message.MessageHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: furina-tea-party </p>
 * <p>Description: </p>
 * <p>Copyright (c) 2024 Karrytech (Shanghai/Beijing) Co., Ltd.</p>
 * <p>All Rights Reserved.</p>
 *
 * @author <a href="mailto:zhangkai@karrytech.com">Zhang Kai</a>
 */
@Component("MessageHandler.broadcast")
public class BroadcastMessageHandler extends MessageHandler {

    @Override
    public void handler(Message message, Selector server, SelectionKey client, BlockingQueue<Task> queue, AtomicInteger onlineUsers) throws InterruptedException {
        try {
            byte[] response = ProtoStuffUtil.serialize(
                    new Response(
                            ResponseHeader.builder().type(ResponseType.NORMAL)
                                    .sender(message.getHeader().getSender())
                                    .timestamp(message.getHeader().getTimestamp()).build(),
                            message.getBody()));
            super.broadcast(response, server);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}